//
//  MYHomeViewController.swift
//  NewMicroblog
//
//  Created by apple on 2016/10/22.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit

let cellIdentifier = "cell"

class MYHomeViewController: MYVisitorController {
    
   var listViewModel = MYListViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()
        if !login {
            visitorView?.setIconViewAndBackView(imageName: nil, title: nil)
            return
        }
        
       
        setupNav()
        
        setTableView()
        
        if let nav = self.navigationController {
            nav.view.insertSubview(tipLabel, belowSubview: nav.navigationBar)
            tipLabel.frame = CGRect(x: 0, y: nav.navigationBar.frame.maxY - 35, width: nav.navigationBar.frame.width, height: 35)
        }
         getUserData()
    }
    
    fileprivate func startTipAnimation(message: String){
        if tipLabel.isHidden == false {
            return
        }
        tipLabel.isHidden = false
        tipLabel.text = message
        UIView.animate(withDuration: 1, animations: {
            self.tipLabel.transform = CGAffineTransform(translationX: 0, y: self.tipLabel.frame.height)
            
            
        }) { (_) in
            
            UIView.animate(withDuration: 1, animations: {
                self.tipLabel.transform = CGAffineTransform.identity
            }, completion: { (_) in
                self.tipLabel.isHidden = true
            })
            
            
        }
    }
    
    
   @objc func sweepClick(){
//        listViewModel.getUserData(isPullUP: , callBack: <#T##(Bool) -> ()#>)
    }
    
    @objc func pushClick(){
        let tempVc = MYTempViewController()
        tempVc.hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(tempVc, animated: true)
    }
    
     /// 设置导航栏
     func setupNav(){
      navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", title:nil, target: self, action: #selector(sweepClick))
      navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", title: nil, target: self, action: #selector(pushClick))
    }
    fileprivate lazy var bottomView: UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
        // 设置颜色
        view.color = UIColor.purple
        return view
    }()
    // 系统的下拉刷新控件
    fileprivate lazy var refreshControl: MYRefreshControl = MYRefreshControl()
    //MARK:-  添加tipLabel
    private lazy var tipLabel: UILabel =  {
        let lab = UILabel(title: "没有加载到最新数据", fontSize: 11, textColor:UIColor.white )
        lab.backgroundColor = UIColor.orange
        lab.textAlignment = .center
        lab.isHidden = true
        return lab
    }()

    
    
    /// 让viewModel去加载数据
    func getUserData(){
    
        listViewModel.getHomeData(isPullUP: bottomView.isAnimating){
        (isSuccess,message) in
        if !self.bottomView.isAnimating {
                self.startTipAnimation(message: message)
            }
        if !isSuccess {
        print("请求数据失败")
        
        }else {
        // 刷新 UI
        self.tableView.reloadData()
        }
        self.endRefreshing()
    }
}

// 停止下拉和上啦动画
func endRefreshing() {
    // 停止动画
    self.bottomView.stopAnimating()
    // 下拉刷新也要停止
    self.refreshControl.endRefreshing()
}


    private func setTableView(){
        tableView.dataSource = self
        tableView.register(MYHomeViewCell.self, forCellReuseIdentifier: cellIdentifier)
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 200
        // 设置 footView
        tableView.tableFooterView = bottomView
        // 添加系统下拉刷新控件
        tableView.addSubview(refreshControl)
        refreshControl.addTarget(self, action: #selector(getUserData), for: UIControlEvents.valueChanged)
    }
}

// MARK: - UITableViewDataSource
extension MYHomeViewController:UITableViewDataSource{

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return listViewModel.dataArr.count
  }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! MYHomeViewCell
        cell.statusViewModel = listViewModel.dataArr[indexPath.row]
        
        return cell
    }
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        // 如果 indexPath.row == 19  -> count - 1 代表显示最后一个 cell
        if indexPath.row == listViewModel.dataArr.count - 1 && !bottomView.isAnimating {
            // 开启动画
            bottomView.startAnimating()
            // 马上请求数据
            getUserData()
        }
    }
    
}

